package com.stedu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stedu.bean.RespBean;
import com.stedu.bean.Teacher;
import com.stedu.exception.SteduException;
import com.stedu.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin/teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;
    @Value("5")
    private Integer pageSize;
    @GetMapping("/selectByPage")
    public RespBean selectByPage(Integer PageNum, String tname){
        if (PageNum==0){
            PageNum=1;
        }
        //currentPage开始页面
        PageHelper.startPage(PageNum,pageSize);
        //查询
        List<Teacher> teacherList = teacherService.selectByTname(tname);
        //封装分页
        PageInfo<Teacher> pageInfo = new PageInfo<>(teacherList, 5);
        return RespBean.ok("成功",pageInfo);
    }
    //加
    @PostMapping("/insert")
    public RespBean insert(@RequestBody @Validated Teacher teacher) throws SQLException, SteduException {
        //添加
        if (teacherService.insert(teacher)){
            return  RespBean.ok("添加成功~~~");
        }
        else {
            return RespBean.error("添加失败，请重新添加");
        }
    }
    //删
    @DeleteMapping("/{tid}")
    public RespBean delete(@PathVariable("tid") Integer tid) throws SteduException {
        //删除
        if (teacherService.delete(tid)){
            return RespBean.ok("删除成功~~~");
        }else{
            return RespBean.error("老师还有课程要交，删除失败");
        }
    }
    //改
    @PutMapping("/update")
    public RespBean update(@RequestBody @Validated  Teacher teacher) throws SteduException {
        //修改
        if (teacherService.update(teacher)){
            return RespBean.ok("修改成功~~~");
        }
        else {
            return RespBean.error("修改失败，请重新修改");
        }
    }

    //查所有
    @GetMapping
    public RespBean selectAll(){
        List<Teacher> teacherList = teacherService.selectAll()
                .stream()
                .filter(e -> e.getCid() !=null && e.getTstate().equals("1") )
                .collect(Collectors.toList());
        return RespBean.ok("", teacherList);
    }

    //根据sid查
    @GetMapping("/{tid}")
    public RespBean selectByTid(@PathVariable("tid") Integer tid){
        Teacher teacher = teacherService.selectByTid(tid);
        return RespBean.ok("", teacher);
    }
}
